Managing HTTP Status Codes and Content Types in Java Servlets
Course: Advanced Java Training
Topic: Managing HTTP Status Codes and Content Types
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to HTTP Status Codes and Content Types
HTTP status codes and content types are essential parts of communication between web browsers, API clients, and Java web applications. In Java Servlet development, they are managed primarily through the HttpServletResponse interface.
When a client sends an HTTP request, the server processes it and returns an HTTP response. The response communicates whether the request succeeded, whether additional action is required, or whether an error occurred. It also identifies the format of the response body so the client can interpret the returned data correctly.
- HTTP status code: A numeric code that describes the result of processing a request.
- Content type: A media type that identifies the format of the response body, such as HTML, JSON, plain text, or PDF.
- HttpServletResponse: The Servlet API interface used to configure response status, headers, content type, and output.
2. Learning Objectives
After studying this topic, learners should be able to:
- Understand the structure and purpose of HTTP status codes.
- Differentiate between informational, successful, redirection, client-error, and server-error responses.
- Set HTTP status codes using Java Servlet methods and constants.
- Configure response content types and character encodings.
- Return HTML, plain text, JSON, and other response formats.
- Handle invalid requests and server errors appropriately.
- Apply status-code and content-type best practices when developing web applications and REST APIs.
3. Understanding HTTP Status Codes
An HTTP status code is a three-digit number included in the server's response status line. It provides a standardized indication of the result of an HTTP request.
For example, when a browser requests a webpage and the server successfully returns it, the server commonly responds with 200 OK. If the requested resource does not exist, the server may respond with 404 Not Found.
HTTP status codes are divided into five major categories.
| Category |
Code Range |
Meaning |
Examples |
| Informational |
100–199 |
The request process is continuing. |
100 Continue |
| Successful |
200–299 |
The request was successfully received or processed. |
200 OK, 201 Created, 204 No Content |
| Redirection |
300–399 |
Additional action or redirection may be needed. |
301 Moved Permanently, 302 Found, 304 Not Modified |
| Client Error |
400–499 |
The request cannot be fulfilled as submitted or access is not permitted. |
400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found |
| Server Error |
500–599 |
The server encountered an error or cannot fulfill a valid request. |
500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable |
4. Common HTTP Status Codes in Java Web Applications
4.1 Successful Responses
| Status Code |
Name |
When to Use |
| 200 |
OK |
A request succeeded and the response contains the expected result. |
| 201 |
Created |
A request successfully created a resource. |
| 202 |
Accepted |
The request was accepted for processing, but processing may not be complete. |
| 204 |
No Content |
The request succeeded and no response body is returned. |
4.2 Redirection Responses
| Status Code |
Name |
When to Use |
| 301 |
Moved Permanently |
A resource has a permanent new URL. |
| 302 |
Found |
A resource is temporarily available at another URL. |
| 303 |
See Other |
The client should retrieve another resource, commonly using GET. |
| 304 |
Not Modified |
A cached representation can be reused under conditional-request rules. |
| 307 |
Temporary Redirect |
A temporary redirect that preserves the HTTP method. |
| 308 |
Permanent Redirect |
A permanent redirect that preserves the HTTP method. |
4.3 Client Error Responses
| Status Code |
Name |
When to Use |
| 400 |
Bad Request |
Request parameters or request data are invalid. |
| 401 |
Unauthorized |
Valid authentication credentials are missing or invalid. |
| 403 |
Forbidden |
The server refuses to authorize the requested action. |
| 404 |
Not Found |
The requested resource does not exist or is not available at the requested URL. |
| 405 |
Method Not Allowed |
The HTTP method is not supported for the requested resource. |
| 409 |
Conflict |
The request conflicts with the current state of a resource. |
| 415 |
Unsupported Media Type |
The request body uses a format the server does not support. |
| 422 |
Unprocessable Content |
The request content is understood but cannot be processed, often because of validation errors. |
| 429 |
Too Many Requests |
The client has sent too many requests within a specified period. |
4.4 Server Error Responses
| Status Code |
Name |
When to Use |
| 500 |
Internal Server Error |
An unexpected server-side failure occurred. |
| 501 |
Not Implemented |
The server does not support the functionality required to fulfill the request. |
| 502 |
Bad Gateway |
A gateway or proxy received an invalid response from an upstream server. |
| 503 |
Service Unavailable |
The server is temporarily unable to handle the request. |
| 504 |
Gateway Timeout |
A gateway or proxy did not receive a timely upstream response. |
5. Managing HTTP Status Codes with HttpServletResponse
Java Servlets provide the HttpServletResponse interface to set status codes. The status should accurately describe the result of processing the request.
5.1 Using setStatus()
The setStatus() method sets the response status code without automatically creating an error page or redirecting the client.
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/status")
public class StatusServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setStatus(
HttpServletResponse.SC_OK
);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().println(
"Request processed successfully."
);
}
}
Explanation:
doGet() processes an HTTP GET request.
SC_OK is a predefined constant representing status code 200.
setStatus() specifies the HTTP status.
setContentType() defines the response media type.
getWriter() writes text to the response body.
5.2 Using Servlet Status Constants
The Servlet API provides named constants for commonly used HTTP status codes. These constants make code easier to read and maintain.
response.setStatus(
HttpServletResponse.SC_CREATED
);
response.setStatus(
HttpServletResponse.SC_BAD_REQUEST
);
response.setStatus(
HttpServletResponse.SC_NOT_FOUND
);
response.setStatus(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR
);
Common constants include SC_OK, SC_CREATED, SC_NO_CONTENT, SC_BAD_REQUEST, SC_UNAUTHORIZED, SC_FORBIDDEN, SC_NOT_FOUND, and SC_INTERNAL_SERVER_ERROR.
Use the constants available in the Servlet API version supported by your application. If a constant is not available in an older API version, verify compatibility before using it.
5.3 Using sendError()
The sendError() method sends an error response with the specified status code. The servlet container may generate an error page or apply configured error-page handling.
@WebServlet("/product")
public class ProductServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String id = request.getParameter("id");
if (id == null || id.isBlank()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Product ID is required."
);
return;
}
// Retrieve the product and process the request.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().println(
"Product request received."
);
}
}
Once sendError() has been called, the response should not be treated as an ordinary response that can continue writing the intended body. Return from the handler after sending the error.
```html
6. Understanding Content Types in HTTP
A content type identifies the media format of the data contained in an HTTP request or response. It is communicated through the Content-Type HTTP header.
For example, when a servlet returns an HTML page, it can specify text/html. When a servlet returns structured API data, it can specify application/json.
6.1 Common Content Types
| Content Type |
Purpose |
Typical Use |
text/html |
HTML document |
Webpages and server-rendered views. |
text/plain |
Plain text |
Simple messages and diagnostic output. |
application/json |
JSON data |
REST APIs and frontend applications. |
application/xml |
XML data |
XML-based integrations. |
text/csv |
Comma-separated values |
Spreadsheet exports and tabular data. |
application/pdf |
PDF document |
Reports, invoices, and downloadable documents. |
application/octet-stream |
Generic binary data |
Binary downloads. |
image/png |
PNG image |
Image delivery. |
application/x-www-form-urlencoded |
URL-encoded form data |
Common HTML form submissions. |
multipart/form-data |
Multipart form data |
File uploads and forms containing files. |
7. Setting Content Types in Java Servlets
The setContentType() method specifies the media type of the response body. It should be called before the response is committed.
7.1 Returning an HTML Response
@WebServlet("/html-response")
public class HtmlResponseServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().println(
"<h1>Welcome to Java Servlets</h1>"
);
response.getWriter().println(
"<p>This is an HTML response.</p>"
);
}
}
The browser interprets the returned content as HTML. In production, dynamic values must be HTML-escaped before being inserted into markup.
7.2 Returning Plain Text
@WebServlet("/text-response")
public class TextResponseServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"Your request was completed successfully."
);
}
}
This response is useful for simple messages, health-check endpoints, and basic demonstrations.
7.3 Returning JSON Data
JSON is widely used when Java backends communicate with JavaScript applications, mobile apps, and external services.
@WebServlet("/api/message")
public class JsonResponseServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(
HttpServletResponse.SC_OK
);
response.getWriter().write(
"{\"status\":\"success\","
+ "\"message\":\"Data retrieved successfully\"}"
);
}
}
The response body contains a JSON object, and the content type tells the client that the returned representation is JSON.
Best practice: Use a JSON serialization library such as Jackson or Gson for real applications. Manually concatenating JSON becomes error-prone when values contain quotation marks, backslashes, or other characters that require escaping.
8. Understanding Character Encoding
Character encoding determines how text characters are represented in bytes. UTF-8 is a widely used encoding that supports a broad range of languages and symbols.
In Java Servlets, configure the response character encoding before obtaining the writer or committing the response.
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.println("<h1>नमस्ते</h1>");
writer.println("<p>Welcome to Java Web Development.</p>");
The output can contain multilingual text when the response is correctly encoded and the browser interprets it using UTF-8.
For form submissions, request encoding is a separate concern. Configure it before reading request parameters when required:
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
Do not confuse request encoding with response encoding: one controls how incoming request data is decoded, while the other controls how outgoing response text is encoded.
9. Understanding the Content-Type Header
The Content-Type header describes the media type of the HTTP message body. In a servlet response, it can be configured using setContentType().
response.setContentType("application/json");
String contentType = response.getContentType();
response.getWriter().write(
"{\"contentType\":\"" + contentType + "\"}"
);
This example illustrates the API method, but the returned JSON should normally be generated using a JSON library rather than string concatenation.
When inspecting a response, developers can use browser developer tools, API clients, or command-line tools to check the status code, content type, and body.
10. Difference Between Content-Type and Accept
Content-Type and Accept are different HTTP headers that serve different purposes.
| Feature |
Content-Type |
Accept |
| Purpose |
Identifies the media type of the message body. |
Indicates which response media types the client can accept. |
| Common direction |
Client to server for request bodies; server to client for response bodies. |
Usually client to server. |
| Example |
Content-Type: application/json |
Accept: application/json |
| Servlet handling |
Configure a response with setContentType(). |
Read the request header using getHeader("Accept") or use API negotiation logic. |
For example, a client may send JSON in the request body and request JSON in the response. The server should validate the request media type and return a response format that is supported by the endpoint and acceptable to the client.
11. Managing Content Types for File Downloads
Java Servlets can return files such as PDFs, CSV reports, and images. The response content type should describe the actual file format. The Content-Disposition header can indicate whether the browser should display or download the content.
response.setContentType("text/csv");
response.setHeader(
"Content-Disposition",
"attachment; filename=\"report.csv\""
);
PrintWriter writer = response.getWriter();
writer.println("Name,Course");
writer.println("Amit,Advanced Java");
writer.println("Priya,Java Servlets");
This example creates a small CSV download. For user-controlled filenames, validate and safely encode the filename rather than placing arbitrary input directly into a response header.
When returning binary files, use response.getOutputStream() and write the file bytes. Do not obtain both the character writer and binary output stream for the same response.
12. Handling Unsupported Media Types
A server can reject a request when the request body uses a media type that the endpoint does not support. HTTP status code 415 Unsupported Media Type is commonly used for this situation.
@WebServlet("/api/data")
public class DataServlet extends HttpServlet {
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String contentType = request.getContentType();
if (contentType == null ||
!contentType.toLowerCase(java.util.Locale.ROOT)
.startsWith("application/json")) {
response.sendError(
HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"This endpoint accepts JSON requests."
);
return;
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"{\"message\":\"JSON content type accepted\"}"
);
}
}
This is an introductory media-type check. A production endpoint must also parse the body, validate the JSON structure, handle malformed input, and enforce appropriate size limits. If a JSON media type includes parameters such as a charset, the application should handle them correctly.
13. Handling Invalid Input with Appropriate Status Codes
Applications should return meaningful status codes when submitted data fails validation. For example, missing required parameters can result in a 400 Bad Request response.
@WebServlet("/api/user")
public class UserServlet extends HttpServlet {
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
if (username == null || username.isBlank()) {
response.setStatus(
HttpServletResponse.SC_BAD_REQUEST
);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"{\"error\":\"Username is required\"}"
);
return;
}
response.setStatus(
HttpServletResponse.SC_CREATED
);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"{\"message\":\"User data validated\"}"
);
}
}
This is a simplified demonstration of response status selection. In a real registration endpoint, use 201 Created only after the resource has actually been created successfully. For a failed validation, return a suitable client-error response.
14. Difference Between setStatus(), sendError(), and sendRedirect()
| Method |
Purpose |
Typical Use |
setStatus() |
Sets the HTTP response status code. |
Returning a custom JSON response with status 400 or 201. |
sendError() |
Sends an error response and clears the response buffer. |
Reporting an invalid request or missing resource using container error handling. |
sendRedirect() |
Redirects the client to another URL. |
Redirecting a user after a form submission. |
Use setStatus() when you need to create a custom response body for the selected status. Use sendError() when container error handling is appropriate. Use sendRedirect() when the client must navigate to another resource.
After calling sendError() or sendRedirect(), return from the handler instead of continuing to write the original response body. Set headers and content types before the response is committed.
15. Configuring Custom Error Pages
Servlet applications can configure custom error pages so users receive a meaningful message instead of a generic server error page.
For example, a deployment descriptor can map a status code to an error page:
<error-page>
<error-code>404</error-code>
<location>/errors/not-found.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/errors/server-error.jsp</location>
</error-page>
Place these elements inside the appropriate web-app element in the application's WEB-INF/web.xml file. The descriptor version and namespace must match the Servlet API and container used by the project.
Custom error pages should avoid displaying stack traces, database details, internal paths, or credentials. Log technical information securely on the server instead.
16. Common Mistakes When Managing Status Codes and Content Types
| Mistake |
Why It Is a Problem |
Recommended Solution |
| Returning 200 for every request |
Clients cannot reliably distinguish success from failure. |
Choose a status code that reflects the actual result. |
| Using 404 for invalid form values |
The resource may exist even though the submitted data is invalid. |
Use 400 or another appropriate validation-related status. |
| Returning JSON with text/html |
Clients may interpret the response incorrectly. |
Set the correct media type, such as application/json. |
| Setting content type after writing output |
The response may already be committed. |
Set status, headers, and content type before writing the body. |
| Mixing getWriter() and getOutputStream() |
The Servlet API does not permit both for the same response. |
Choose the correct output mechanism for text or binary content. |
| Returning detailed exception messages |
Internal implementation details may be exposed. |
Return safe messages and log diagnostic details privately. |
| Ignoring malformed request data |
Invalid input may cause unexpected errors. |
Validate and parse incoming data defensively. |
| Manually concatenating complex JSON |
Special characters may produce invalid JSON. |
Use a JSON serialization library. |
17. Best Practices
- Use standard HTTP status codes consistently across the application.
- Return
201 Created when a resource is actually created, and consider a Location header when appropriate.
- Use
204 No Content only when no response body is being returned.
- Set the response content type according to the actual body format.
- Configure UTF-8 encoding for text responses where appropriate.
- Set response headers before writing or committing the response.
- Validate the request's
Content-Type when the endpoint expects a particular request-body format.
- Consider the client's
Accept header when supporting multiple response formats.
- Return structured error responses for APIs when consistent error handling is required.
- Avoid exposing stack traces, sensitive information, and internal server details.
- Test successful requests, invalid input, unsupported media types, missing resources, and unexpected server failures.
- Use the Servlet API version compatible with the application's Java and servlet-container versions.
18. Practical Mini Project: HTTP Response Demonstration
Create a servlet that returns different response formats and status codes according to the URL path. This exercise helps you practice configuring responses in Java.
Example Servlet
@WebServlet("/demo-response")
public class ResponseDemoServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String type = request.getParameter("type");
if (type == null) {
response.setStatus(
HttpServletResponse.SC_BAD_REQUEST
);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"Provide a type parameter: text or json."
);
return;
}
if ("text".equalsIgnoreCase(type)) {
response.setStatus(
HttpServletResponse.SC_OK
);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"This is a plain-text response."
);
return;
}
if ("json".equalsIgnoreCase(type)) {
response.setStatus(
HttpServletResponse.SC_OK
);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(
"{\"status\":\"success\","
+ "\"format\":\"json\"}"
);
return;
}
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Unsupported type. Use text or json."
);
}
}
Testing the Servlet
- Request
/demo-response?type=text to receive a plain-text response.
- Request
/demo-response?type=json to receive JSON data.
- Request
/demo-response without a parameter to receive a 400 response.
- Request
/demo-response?type=xml to receive an error for the unsupported type.
Remember to include the application's context path in the URL when running the servlet on a local server.
19. Practice Exercises
- Create a servlet that returns status code 200 and an HTML welcome page.
- Create an endpoint that returns status code 201 after successfully creating a sample resource.
- Build a JSON endpoint that returns a 400 status when a required parameter is missing.
- Create a CSV download endpoint using the correct content type and content-disposition header.
- Configure custom error pages for HTTP 404 and HTTP 500.
- Create an endpoint that rejects unsupported request media types with status 415.
- Test the differences between
setStatus(), sendError(), and sendRedirect().
- Use a browser developer tool or an API client to inspect response headers and status codes.
20. Interview Questions and Answers
Q1. What is an HTTP status code?
Answer: It is a three-digit code in an HTTP response that indicates whether the request succeeded, requires redirection, or encountered an error.
Q2. What are the five categories of HTTP status codes?
Answer: Informational (1xx), successful (2xx), redirection (3xx), client error (4xx), and server error (5xx).
Q3. What is the purpose of setStatus()?
Answer: It sets the HTTP status code on the response without automatically generating an error page or redirecting the client.
Q4. What is the difference between setStatus() and sendError()?
Answer: setStatus() sets the response status and allows the application to construct its response body. sendError() sends an error response and invokes the container's error-handling behavior where configured.
Q5. What is a content type?
Answer: A content type identifies the media format of a message body, such as HTML, JSON, plain text, or PDF.
Q6. How do you set JSON content in a servlet response?
Answer: Call response.setContentType("application/json") and configure the character encoding before writing the JSON response body.
Q7. What is the difference between Content-Type and Accept?
Answer: Content-Type describes the media type of the message body, whereas Accept indicates the response media types that a client can accept.
Q8. When should HTTP 201 be used?
Answer: It should be used when a request successfully creates a resource.
Q9. When should HTTP 204 be used?
Answer: It indicates that the request succeeded and the response contains no body.
Q10. Why is UTF-8 important in servlet applications?
Answer: UTF-8 supports many languages and symbols and helps ensure text is encoded and decoded consistently.
Q11. What does HTTP 415 mean?
Answer: It means the server refuses to process the request because its media type is unsupported for that endpoint.
Q12. When should HTTP 500 be returned?
Answer: It indicates an unexpected server-side failure. Applications should log diagnostic details securely and avoid exposing internal exception information to clients.
21. Quick Revision Checklist
- Understand the five categories of HTTP status codes.
- Know the common status codes 200, 201, 204, 301, 302, 400, 401, 403, 404, 405, 415, 429, and 500.
- Use
HttpServletResponse.setStatus() to set a response status.
- Use
sendError() when container error handling is appropriate.
- Use
setContentType() to specify the response media type.
- Configure character encoding before obtaining the writer.
- Differentiate between the request's Content-Type and Accept headers.
- Return the appropriate media type for HTML, JSON, text, and downloadable files.
- Set headers before the response is committed.
- Validate request data and handle errors securely.
22. Conclusion
Managing HTTP status codes and content types is an essential skill in Java Servlet and Advanced Java development. Status codes communicate the outcome of a request, while content types identify the format of the returned data.
By using HttpServletResponse correctly, developers can build reliable web applications and APIs that return meaningful success responses, handle errors consistently, and provide content in formats that clients can process.
Practice these concepts through servlet exercises and small projects to strengthen your understanding of HTTP communication, response handling, and enterprise Java web development.
Explore the Advanced Java Training Course at JustAcademy to continue learning about Servlets and enterprise application development.
Register for a Course Demo to learn more about the training program, or visit the JustAcademy website.